import React, { Component } from 'react'
import PropTypes from 'prop-types'
import axios from 'axios';
import PubSub from 'pubsub-js'

import './main.css';
class Main extends Component {
    // static propTypes = {
    //     name: PropTypes.string.isRequired
    // }
    state = {
        userArry: null,
        // 没有关键字
        haskey: false,
        // 没有数据
        isempty: false
    }
    componentDidMount() {
        PubSub.subscribe('my-search', (msg, name) => {
            console.log(msg,name)
            const { isempty, haskey } = this.state
            this.setState({ haskey: true })
            // const { name } = newprps
            const url = `https://api.github.com/search/users?q=${name}`
            axios.get(url).then((response) => {
                let items = response.data.items;
                if (items.length == 0) {
                    this.setState({ haskey: false })
                    return
                }
                const users = items.map(item => {
                    return { name: item.login, url: item.html_url, avatarUrl: item.avatar_url }
                })
                this.setState({ userArry: users, isempty: true })
            }).catch(error => {
                console.log(error.message);
            })
        });
    }

    // UNSAFE_componentWillReceiveProps(newprps) {
    //     const { isempty, haskey } = this.state
    //     this.setState({ haskey: true })
    //     const { name } = newprps
    //     const url = `https://api.github.com/search/users?q=${name}`
    //     axios.get(url).then((response) => {
    //         let items = response.data.items;
    //         if (items.length == 0) {
    //             this.setState({ haskey: false })
    //             return
    //         }
    //         const users = items.map(item => {
    //             return { name: item.login, url: item.html_url, avatarUrl: item.avatar_url }
    //         })
    //         this.setState({ userArry: users, isempty: true })
    //     }).catch(error => {
    //         console.log(error.message);
    //     })
    // }

    render() {
        const { userArry, haskey, isempty } = this.state
        if (!haskey) {
            return <h2>请输入关键字</h2>
        } else if (!isempty) {
            return <h2>请稍等。。。。。</h2>
        } else {
            return (
                <div className="row">
                    {
                        userArry.map((user, index) => {
                            return (<div className="card" key={index}>
                                <a href={user.url} target="_blank">
                                    <img src={user.avatarUrl} style={{ "width": "100px" }} />
                                </a>
                                <p className="card-text">{user.name}</p>
                            </div>)
                        })
                    }
                </div>
            )
        }

    }
}

export default Main
